<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生名单</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin: 20px;
        }

        textarea {
            width: 300px;
            height: 150px;
        }

        button {
            margin-top: 10px;
            padding: 8px 16px;
            font-size: 16px;
            cursor: pointer;
        }

        #winner {
            margin-top: 20px;
            font-size: 24px;
            color: green;
            font-weight: bold;
        }
    </style>
</head>

<body>

    <h1>学生名单管理</h1>

    <label for="studentList">学生名单：</label>
    <br>
    <textarea id="studentList"></textarea>
    <br>
    <button onclick="saveStudentList()">保存</button>
    <button onclick="randomDraw()">随机点名</button>
    <div id="winner"></div>

    <script>
        // 加载保存的学生名单、权重信息
        window.onload = function () {
            const textarea = document.getElementById("studentList");
            textarea.value = Object.keys(loadStudentData())
        };

        // 保存学生名单到本地存储
        function saveStudentList() {
            const data = loadStudentData()
            const inputStr = document.getElementById("studentList").value;
            inputStr.split(',').forEach(student => {
                if (!data[student]) {
                    data[student] = 0;
                }
            });

            localStorage.setItem("studentData", JSON.stringify(data));
            alert("学生名单已保存！");
        }

        function updateStudentData(student) {
            const data = loadStudentData()
            if (data[student] || data[student] === 0) {
                data[student] += 1;
            }
            localStorage.setItem("studentData", JSON.stringify(data));
        }

        // 从本地存储加载学生名单
        function loadStudentData() {
            const studentData = localStorage.getItem("studentData");

            return studentData ? JSON.parse(studentData) : {};
        }

        // 获取总权重
        function getTotalDraw() {
            const studentData = loadStudentData()
            let totalDraw = 0;

            for (const student in studentData) {
                totalDraw += studentData[student];
            }
            return totalDraw;
        }

        // 随机点名
        async function randomDraw() {
            const winnerElement = document.getElementById("winner");
            winnerElement.style.color = '#aaa'
            const poolList = generatePoolList()

            let count = 0;
            let selectedStudent;
            do {
                selectedStudent = await getRandomStudent(poolList);
                console.log(`第 ${count + 1} 次点名：${selectedStudent}`);
                winnerElement.innerText = selectedStudent;
                count++;
            } while (count < 20);

            winnerElement.innerText = `点名结束, 结果: ${selectedStudent}`;
            winnerElement.style.color = '#f66'
            updateStudentData(selectedStudent)
        }

        // 生成点名池
        function generatePoolList() {
            const studentData = loadStudentData()
            const totalDraw = getTotalDraw()
            const poolList = []
            for (const student in studentData) {
                const occurrences = Math.round(totalDraw ? (1 - studentData[student] / totalDraw) * 100 : 100)
                // 创建一个有 occurrences 次数重复的 student 组成的数组
                poolList.push(...Array.from({ length: occurrences }, () => student))
            }
            return poolList
        }

        // 异步获取随机学生
        function getRandomStudent(list) {
            return new Promise((resolve) => {
                const delay = Math.floor(Math.random() * 80) + 80;
                setTimeout(() => {
                    const randomIndex = Math.floor(Math.random() * list.length);
                    resolve(list[randomIndex]);
                }, delay);
            });
        }
    </script>

</body>

</html>
